package org.lt.resume.controller.user;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lt.resume.domain.users.User;
import org.lt.resume.service.userserviceInterface.UserServiceInterface;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class RegisterUserController extends AbstractController{

	/** **/
	private static final long serialVersionUID = 2122607117576811468L;

	private UserServiceInterface userservice;
	
	
	
//	@Override
//	protected void service(HttpServletRequest request, HttpServletResponse response)
//			throws ServletException, IOException {
//		String username = request.getParameter("username");
//		String password = request.getParameter("password");
//		String memo = request.getParameter("memo");
//		User user = new User();
//		user.setUsername(username);
//		user.setPassword(password);
//		user.setMemo(memo);
//		if (!userservice.hasMatchUser(username)){
//			userservice.registerUser(user);
////			response.getWriter().write("Regist Success");
//			response.sendRedirect("success.html");
//		}
//		response.sendRedirect("error.html");
//
//	}


	public String registerUser(HttpServletRequest request) {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String memo = request.getParameter("memo");
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setMemo(memo);
		if (!userservice.hasMatchUser(username)){
			userservice.registerUser(user);
//			response.getWriter().write("Regist Success");
			return "success";
		}
		return "error";
	}
	
	
	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		String username = request.getParameter("username");
		String password = request.getParameter("password");
		String memo = request.getParameter("memo");
		User user = new User();
		user.setUsername(username);
		user.setPassword(password);
		user.setMemo(memo);
		if (!userservice.hasMatchUser(username)){
			userservice.registerUser(user);
			RequestDispatcher dispatcher = request.getRequestDispatcher("/success.jsp");
			dispatcher .forward(request, response);
			return null;
//			return new ModelAndView("success");
		}

		return new ModelAndView("error");
	}
	

	public UserServiceInterface getUserservice() {
		return userservice;
	}
	public void setUserservice(UserServiceInterface userservice) {
		this.userservice = userservice;
	}

}
